package microcredit.gui.editor;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.KeyboardFocusManager;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import microcredit.gui.selector.AbstractActionPanel;
import microcredit.gui.util.ColorConstants;

public abstract class AbstractEditorForm<E> extends AbstractActionPanel {

	private String title;
	private ImageIcon icon;
	
	private Component lastFocusOwner;
	
	public AbstractEditorForm() {
		super();
		setBackground(ColorConstants.BACKGROUND_TABBED_PANE);
		//TODO add component focus tracking for this component
	}
	
	public boolean onSave(E element) throws Throwable {
		return true;
	}
	
	public void afterSave(E element) throws Throwable {
		
	}
	
	public ImageIcon getIcon() {
		return icon;
	}
	public void setIcon(ImageIcon icon) {
		ImageIcon oldIcon = this.icon;
		this.icon = icon;
		firePropertyChange("icon", oldIcon, icon);
	}
	
	public String getTitle() {
		return title;
	}
	
	public void setTitle(String title) {
		String oldTitle = this.title;
		this.title = title;
		firePropertyChange("title", oldTitle, title);
	}
	
	public void storeFocusOwner() {
		Component focusOwner = KeyboardFocusManager
				.getCurrentKeyboardFocusManager().getFocusOwner();
		
		if (focusOwner != null && SwingUtilities.isDescendingFrom(focusOwner, this)) {
			this.lastFocusOwner = focusOwner;
		} 
	}
	
	public void focusDefault() {
	}
	
	public Dimension getDefaultSize() {
		return null;
	}
	
	public void restoreFocusOwner() {
		if (lastFocusOwner != null) {
			lastFocusOwner.requestFocus();
		} else {
			focusDefault();
		}
	}
	
//	public JComponent getLastFocusOwner() {
//		if (lastFocusOwner == null) {
//			return getInitialFocusOwner();
//		}
//		return lastFocusOwner;
//	}
//	
//	public abstract JComponent getInitialFocusOwner();
	
	public abstract void apply(E e) throws Throwable ;
	
	public abstract E receive(E e) throws Throwable;
	
}
